/* ------------------------------------------------------------
 *  Bunny project - Data entry component
 *
 * ------------------------------------------------------------ 
 */

// size of grid (in pixels) displayed in the UI
final int	GRID_WIDTH	=	600;
final int	GRID_HEIGHT	=	300;

// size of application
final int 	APP_WIDTH	=	700;
final int	APP_HEIGHT	=	400;

// file names
final String	DATA_FILENAME	=	"data/heat-map.txt";
final String	SEND_UPDATES_TO	=	"131.193.77.183";

DataStore	theData = null;
Grid		theGrid	= null;
EntryBox		entry = null;
PApplet		myApp = null;
boolean		firstUpdate = false;

void setup()
{
	myApp = this;
	
	// specify size of app
	size(APP_WIDTH, APP_HEIGHT);
	smooth();
	
	// load data
	theData = new DataStore();
	theData.loadFile(DATA_FILENAME);

	// make grid
	theGrid = new Grid( theData, 15, 15, GRID_WIDTH, GRID_HEIGHT );
	entry = new EntryBox();
	
}

void draw()
{
	background(200);
	
	theGrid.render();
	entry.render();
}

void keyPressed()
{
	if (!entry.keyPressed())
	{
		if (key == 'c' || key == 'C')
		{
			theData.makeEmpty(theData.getRows(), theData.getCols());
			theData.saveFile(DATA_FILENAME);
			
			if (SEND_UPDATES_TO.length() > 0)
			{
				theData.sendToNetwork( myApp, SEND_UPDATES_TO );
			}
		}
	}
	
}

void mouseClicked()
{
	if (entry.isVisible() == true)
	{
		int midX = width/2;
		int midY = height/2;
		
		if (mouseX >= midX - ENTRY_BOX_WIDTH/2 && mouseX <= midX + ENTRY_BOX_WIDTH/2
		 && mouseY >= midY - ENTRY_BOX_HEIGHT/2 && mouseY <= midY + ENTRY_BOX_HEIGHT/2)
	 	{
	 		// within box, do nothing
	 	}
	 	else
	 	{
	 		// click outside box, hide it
	 		entry.hide();
	 	}
	}
	else
	{
		PVector index = theGrid.highlightedIndex;
		if (index != null)
		{
			entry.setEntryIndex( (int) index.x, (int) index.y );
		}
	}
}
